package com.wsgalaxy.anmanager;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by wssxk on 9/24/17.
 */

public class MainService extends Service {

    MainActivity.MACallback ma_callback = null;
    MSBinder ms_binder = new MSBinder();
    ExecutorService thread_pool = Executors.newCachedThreadPool();

    SocketHandler socket_handler = new SocketHandler();
    ProcessHandler process_handler = new ProcessHandler();

    SocketThread service_thread = new SocketThread();

    public void onCreate() {
        super.onCreate();
        Log.d("wssxk", "startservice");
        service_thread.start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return ms_binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    public class MSBinder extends Binder {
        public void setCallback(MainActivity.MACallback callback) {
            MainService.this.ma_callback = callback;
        }

    }

    public class SocketHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    public class ProcessHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            if (ma_callback != null) {
                ma_callback.addText((String) data.getCharSequence("json"));
            }

        }
    }

    public class SocketThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                ServerSocket server = new ServerSocket(AnGlobal.port);
                Socket socket;

                while (true) {
                    socket = server.accept();
                    thread_pool.execute(new SocketProcess(socket, process_handler, MainService.this));
                    Log.d("wssxk", "accepted");
                }
            } catch (IOException e) {
                Log.d("wssxk", "IOException: " + e.getMessage() );
            } catch (SecurityException e) {
                Log.d("wssxk", "SecurityException: " + e.getMessage());
            } catch (Exception e) {
                Log.d("wssxk", "Exception");
            }

        }
    }
}
